package com.xy.biz.auth.service.impl;

import com.xy.biz.auth.domain.bo.UserPasswordBO;
import com.xy.biz.auth.domain.req.ModifyPasswordRequest;
import com.xy.biz.auth.domain.utils.PasswordUtils;
import com.xy.biz.auth.manager.UserPasswordManager;
import com.xy.biz.auth.service.UserPasswordService;
import com.xy.biz.uc.client.UserClient;
import com.xy.biz.uc.domain.dto.UserDTO;
import com.xy.biz.uc.domain.req.GetUserRequest;
import com.xy.biz.uc.domain.req.SaveUserRequest;
import com.xy.lang.domain.Result;
import com.xy.lang.util.ResultUtils;
import com.xy.tool.context.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
public class UserPasswordServiceImpl implements UserPasswordService, InitializingBean {

    @Autowired
    private UserPasswordManager userPasswordManager;
    @Autowired
    private UserClient userClient;

    private Pbkdf2PasswordEncoder passwordEncoder;

    @Override
    public void afterPropertiesSet() throws Exception {
        passwordEncoder = new Pbkdf2PasswordEncoder();
        passwordEncoder.setAlgorithm(Pbkdf2PasswordEncoder.SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA512);
    }

    @Override
    public int updateUserPassword(Long userId, String password) {
        UserPasswordBO userPasswordBO = UserPasswordBO.builder()
                .userId(userId)
                .password(passwordEncoder.encode(password))
                .updateTime(LocalDateTime.now())
                .build();
        return userPasswordManager.updateUserPassword(userPasswordBO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> personalPasswordModify(ModifyPasswordRequest request) {
        //获取当前用户密码
        UserPasswordBO userPasswordBO = userPasswordManager.getUserPassword(UserContextHolder.getUserId());
        //判断旧密码是否正确
        if (passwordEncoder.matches(request.getOldPassword(), userPasswordBO.getPassword())) {
            //构建用用户密码信息
            UserPasswordBO modifyUserPasswordBO = UserPasswordBO.builder()
                    .userId(UserContextHolder.getUserId())
                    .password(passwordEncoder.encode(request.getPassword()))
                    .updateTime(LocalDateTime.now())
                    .build();
            //更新密码信息
            int row = userPasswordManager.updateUserPassword(modifyUserPasswordBO);
            if (row > 0) {
                UserDTO userDTO = ResultUtils.get(userClient.getUser(GetUserRequest.builder().userId(UserContextHolder.getUserId()).build()));
                if (request.getOldPassword().equals(userDTO.getInitialPassword())) {
                    userClient.updateUserBaseInfo(SaveUserRequest.builder().userId(UserContextHolder.getUserId()).initialPassword("0").build());
                }
                return Result.success();
            }
        }
        return Result.fail(null, "旧密码错误");
    }

}
